﻿using System;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using VideoClipNameHelper;

namespace SyncWithDb
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly SynchronizationContext syncContext;

        private ConfigPaths cp = new ConfigPaths();

        public MainWindow()
        {
            InitializeComponent();
            //
            syncContext = SynchronizationContext.Current;
            //
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //
            try
            {
                ConfigData.ReadConfig(cp);
            }
            catch
            {
                MessageBox.Show(ConfigData.ConfigFileName, "ERROR", MessageBoxButton.OK);
                //--Application.Current.Shutdown(-1);
                //--Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
                //Application.Current.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
                Application.Current.MainWindow.Close();
                //System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            //
            //
            w1.Title = string.Join("; ", (from x in cp.SourceDirs select System.IO.Path.GetFileName(x)).ToArray());
            foreach (string d in cp.SourceDirs)
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { Watch(d); }));
            }
            //
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public void Watch(string dir)
        {
            FileSystemWatcher watcher = new FileSystemWatcher(dir, "*.mkv") { NotifyFilter = NotifyFilters.FileName, IncludeSubdirectories=true };

            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            watcher.EnableRaisingEvents = true;
            Task.Delay(-1);
        }

        private void OnRenamed(object source, RenamedEventArgs e)
        {
            syncContext.Post(o => tbInfo.Text = $"[{e.OldFullPath}]\n=>\n[{e.FullPath}]", null);
            //
            //
            string fnOld = VideoClipData.GetNameWithoutResolution(e.OldFullPath);
            string fnNew = VideoClipData.GetNameWithoutResolution(e.FullPath);
            //string path = System.IO.Path.GetDirectoryName(vfDisk.PathName);
            string zzz = CDBHandler.DbInfo();
            CDBHandler.UpdateClipName(fnOld, fnNew);
            //
        }

        }//class
}//namespace
